package com.example.bbs.web.servlet; /**
 * @auther: zhangxin
 * @Description:
 */

import com.alibaba.fastjson.JSON;
import com.example.bbs.model.Block;
import com.example.bbs.model.Post;
import com.example.bbs.model.Reply;
import com.example.bbs.model.User;
import com.example.bbs.service.BlockService;
import com.example.bbs.service.PostService;
import com.example.bbs.service.ReplyService;
import com.example.bbs.service.UserService;
import com.example.bbs.service.impl.BlockServiceImpl;
import com.example.bbs.service.impl.PostServiceImpl;
import com.example.bbs.service.impl.ReplyServiceImpl;
import com.example.bbs.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "PostDetailServlet", value = "/bbs/postDetailAjax")
public class PostDetailAjaxServlet extends HttpServlet {
    ReplyService replyService = new ReplyServiceImpl();
    UserService userService = new UserServiceImpl();
    PostService postService = new PostServiceImpl();
    BlockService blockService = new BlockServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");
        int pid = Integer.parseInt(req.getParameter("pid"));
        List<Reply> replys = replyService.getReplyList(pid);
        Post post = postService.getPostById(pid);
        User postUser = userService.findUserByPostId(pid);
        post.setAuthor(postUser);
        Block block = blockService.findBlockById(post.getBlockId());

        for(int i = 0; i < replys.size(); i++){
            User user = userService.findUserById(replys.get(i).getUserId());
            replys.get(i).setAuthor(user);
        }
        Map<String,Object> maps = new HashMap<>();
        maps.put("replys",replys);
        maps.put("post",post);
        maps.put("block",block);
        String json = JSON.toJSONStringWithDateFormat(maps,"yyyy-MM-dd HH:mm:ss");
        resp.getWriter().write(json);
    }
}
